<?php

/**
 * Created by PhpStorm.
 * User: DD
 * Date: 2016/4/18
 * Time: 13:34
 */
namespace app\admin\services;

use app\common\model\RoleMenu;
use app\common\services\LoginService;
use app\common\services\BaseService;
use app\common\util\MenuManager;
use think\Db;
use think\Model;

class MenuService extends BaseService
{

    /**
     * @var Model
     */
    private $_model;

    protected function _init()
    {

    }


    public function getMenuList($checkPower = true, $role_ids = '')
    {
        if ($checkPower) {
            if (!is_array($role_ids)) {
                if (is_string($role_ids)) {
                    $role_ids = explode(',', $role_ids);
                } else {
                    $role_ids = [$role_ids];
                }
            }
            $tokensRows = RoleMenu::instance()->where(['role_id' => ['in', $role_ids]])->field('distinct(menu_token) menu_token')->select();
            $tokens = [];
            foreach ($tokensRows as $row) {
                $tokens[] = $row['menu_token'];
            }
            return MenuManager::getMenus($tokens);
        }
        return MenuManager::getMenus(false);

    }

    public function pagination($page, $rows, $sort, $order, $filterRules)
    {
        $viewInstance = $this->_getViewInstance();
        $pid = I('pid', 0, 'intval');
        $filterRules = $this->parseFilterRules($filterRules);
        return [
            $viewInstance->where($filterRules)->where("parent_id=$pid or id=$pid")->count(),
            $viewInstance->where($filterRules)->where("parent_id=$pid or id=$pid")->limit(($page - 1) * $rows, $rows)->select()
        ];
    }

    public function getRoleMenusByPId($_pid = 0)
    {
        $db = $this->_model;
        if (!LoginService::isSuperMan()) {
            $role_ids = LoginService::getLoginUser('role_ids');
            if (!$role_ids) {
                return array();
            }
            $where = 'is_valid=1 and exists(select * from role_menu rm where rm.menu_id=menu.id and role_id in(' . $role_ids . '))';
        } else {
            $where = 'is_valid=1';
        }
        $menus = $db->field('id,title as text,url,parent_id')
            ->where($where)
            ->order('sort desc,id asc')->select();
        $temp = array();
        $childName = 'children';
        foreach ($menus as $m) {
            $pid = $m['parent_id'];
            $id = $m['id'];
            $m['url'] = trim($m['url']);
            if ($m['url'] && strpos($m['url'], '://') === false) {
                $m['url'] = U($m['url']);
            }
            if (isset($temp[$id])) {
                $m[$childName] = $temp[$id][$childName];
            }
            $temp[$id] = $m;
            if ($pid > 0 && $pid != $id) {
                if (!isset($temp[$pid])) {
                    $temp[$pid] = array();
                }
                if (!isset($temp[$pid][$childName])) {
                    $temp[$pid][$childName] = array();
                }
                $temp[$pid][$childName][] = &$temp[$id];
            }
        }
        $_temp = array();
        foreach ($temp as $key => $m) {
            if (!isset($m['parent_id']) || $m['parent_id'] != $_pid || $m['parent_id'] == $m['id']) {
                unset($temp[$key]);
            } else {
                $_temp[] = $m;
            }
        }
        return $_temp;
    }

    public function getMenusByParentId($_pid, $model = null)
    {
        $whereArr = array('is_valid' => 1);
        if ($model == 'front_menu') {
            $whereArr['site_id'] = session('site_id') ?: 0;
        }
        $db = $model ? M($model) : $this->_model;
        $menus = $db->field('id,title as text,url,parent_id')
            ->where($whereArr)
            ->order('sort desc,id asc')
            ->select();
        $temp = array();
        $childName = 'children';
        foreach ($menus as $m) {
            $pid = $m['parent_id'];
            $id = $m['id'];
            $m['url'] = trim($m['url']);
            if ($m['url'] && strpos($m['url'], '://') === false) {
                $m['url'] = U($m['url']);
            }
            if (isset($temp[$id])) {
                $m[$childName] = $temp[$id][$childName];
            }
            $temp[$id] = $m;
            if ($pid > 0 && $pid != $id) {
                if (!isset($temp[$pid])) {
                    $temp[$pid] = array();
                }
                if (!isset($temp[$pid][$childName])) {
                    $temp[$pid][$childName] = array();
                }
                $temp[$pid][$childName][] = &$temp[$id];
            }
        }
        $_temp = array();
        foreach ($temp as $key => $m) {
            if (!isset($m['parent_id']) || $m['parent_id'] != $_pid || $m['parent_id'] == $m['id']) {
                if (empty($temp[$key][$childName])) {
                    $temp[$key]['icon'] = 'none';
                }
                unset($temp[$key]);
            } else {
                $m['state'] = ['opened' => true];
                $_temp[] = $m;
            }
        }
        return $_temp;
    }

    public function getMenusByRoleId($_roleid)
    {
        $db = $this->getModelInstance();
        $menus = $db->alias('m')->join('__ROLE_MENU__ rm on rm.menu_id=m.id and rm.role_id=' . $_roleid, 'LEFT')
            ->field('m.id,m.title as text,m.url,m.parent_id,rm.role_id')
            ->where(array('is_valid' => 1))
            ->order('sort desc,id asc')
            ->select();

        $temp = array();
        $childName = 'children';
        foreach ($menus as $m) {
            $pid = $m['parent_id'];
            $id = $m['id'];
            if ($m['role_id']) {
                $m['checked'] = true;
            }
            $m['url'] = trim($m['url']);
            if ($m['url'] && strpos($m['url'], '://') === false) {
                $m['url'] = U($m['url']);
            }
            if (isset($temp[$id])) {
                $m[$childName] = $temp[$id][$childName];
            }
            $temp[$id] = $m;
            if ($pid > 0 && $pid != $id) {
                if (!isset($temp[$pid])) {
                    $temp[$pid] = array();
                }
                if (!isset($temp[$pid][$childName])) {
                    $temp[$pid][$childName] = array();
                }
                $temp[$pid][$childName][] = &$temp[$id];
            }
        }
        $_temp = array();
        foreach ($temp as $key => $m) {
            if ($m['parent_id'] != 0 || $m['parent_id'] == $m['id']) {
                unset($temp[$key]);
            } else {
                $_temp[] = $m;
            }
        }
        return $_temp;
    }
}